package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.GeneralRequest.GeneralRequest;
import com.mp.approvalreq.service.ReadTemplateServicePrx;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 给其他工程计算审批流的
 * 进销存啊这些
 *
 * @author Administrator
 */
@WebServlet("/getGeneralRequestFlow")
public class GetGeneralRequestFlow extends AbstractServlet {
	
	private static final long serialVersionUID = -6524473373623928868L;
	
	private static final Logger logger = LoggerFactory.getLogger(GetGeneralRequestFlow.class);
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	/**
	 * 数据需要为：{project:}
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			User user = getReqUser(req);
			
			GeneralRequest request = getGeneralRequest(req);
			check(request);
			
			ReadTemplateServicePrx readTemplateServicePrx = ServiceUtils.getReadTemplateServicePrx();
			request = readTemplateServicePrx.getGeneralRequestFlow(request, user);
			
			returnResponse(resp, request);
		} catch (Throwable e) {
			onThrowable(req, resp, e);
		}
	}
	
	private void returnResponse(HttpServletResponse resp, GeneralRequest request) throws IOException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", "0");
		jsonObject.put("res_info", "提交成功");
		jsonObject.put("item", request);
		
		logger.info(jsonObject.toJSONString());
		
		printJson(resp, jsonObject.toJSONString());
	}
	
	private GeneralRequest getGeneralRequest(HttpServletRequest req) throws IOException {
		String reqBody = getContent(req);
		logger.info("json参数 {}", reqBody);
		
		GeneralRequest request;
		try {
			request = JSONObject.parseObject(reqBody, GeneralRequest.class);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new RpcServerLogicalException(1, "请求参数格式错误");
		}
		return request;
	}
	
	protected void check(GeneralRequest generalRequest) {
		if (generalRequest.getProject() < 1) {
			throw new RpcServerLogicalException(1, "工程参数出错");
		}
	}
}
